define(['jquery', 'bootstrap', 'backend', 'table', 'form', '/assets/addons/kuerp/layui/layui.js'], function ($, undefined, Backend, Table, Form, Layui) {

    var Controller = {
        index: function () {

            layui.use(['table','upload','form'], function(){
                var table = layui.table;
                upload = layui.upload;

                var set = Config.set;
                var examine = parseInt(set.examine.is_checked);
                if(isNaN(examine)){
                    examine = 0;
                }
                if(examine!=1){
                    hideStatus = true;
                }else{
                    hideStatus = false;
                }
                var taxes = parseInt(set.taxes.is_checked);
                if(isNaN(taxes)){
                    taxes = 0;
                }
                if(taxes!=1){
                    taxesStatus = true;
                }else{
                    taxesStatus = false;
                }
                var price_decimal = parseInt(set.price_decimal.value);
                if(isNaN(price_decimal)){
                    price_decimal = 1;
                }
                var number_decimal = parseInt(set.number_decimal.value);
                if(isNaN(number_decimal)){
                    number_decimal = 1;
                }

                var isReloading = false; // 标志位，防止重复加载
                table.render({
                    elem: '#table'
                    ,url:'kuerp/goods_sales_info/index'
                    ,parseData: function(res){ //res 即为原始返回的数据
                        return {
                            "code": 0, //解析接口状态
                            "msg": '', //解析提示文本
                            "count": res.total, //解析数据长度
                            "data": res.rows //解析数据列表
                         };
                    }
                    ,toolbar: '#thisToolbar' //开启头部工具栏，并为其绑定左侧模板
                    ,height: 'full-180'
                    ,page: true
                    ,limit: 50
                    ,limits: [10,20,30,50,100,150, 200]
                    ,cellMinWidth: 100 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    ,cols: [[
                        {field: 'purchase_time', title: __('Purchase_time'),width:120,templet: function (d) {
                                return layui.util.toDateString(d.purchase_time*1000,'yyyy-MM-dd');
                            }},
                        {field: 'purchase_code', title: __('Purchase_code'), width:170},
                        {field: 'purchase_type', title: __('Purchase_type'),templet: function (d) {
                            if(d.purchase_type==1){
                                return __('Purchase_type 1');
                            }
                            if(d.purchase_type==2){
                                return __('Purchase_type 2');
                            }
                        }},
                        
                        {field: 'staff_member.name', title: __('Sale_user'),templet: function (d) {
                                if(d.staff_member.name!=null){
                                    return d.staff_member.name;
                                }else{
                                    return '';
                                }
                            }},
                        {field: 'customers.customer_name', title: __('Customers_id'),templet: function (d) {
                                if(d.customers.customer_name!=null){
                                    return d.customers.customer_name;
                                }else{
                                    return '';
                                }
                            },minWidth:150},
                        {field: 'goods_code', title: __('Goods_code'), operate: 'LIKE'},
                        {field: 'goods.goods_name', title: __('Goods_name'),templet: function (d) {
                                return d.goods.goods_name;
                            }},
                        {field: 'goods_type', title: __('购买类型')},
                        {field: 'goods.barcode', title: __('Goods_barcode'),width:100,templet: function (d) {
                                return d.goods.goods_barcode;
                            }, hide:true},
                        {field: 'goods.goods_specification_id', title: __('Goods_specification_id'),width:100,templet: function (d) {
                                return d.goods.goods_specification_id;
                            }, hide:true},
                        {field: 'unit.name', title: __('Unitname'),width:100,templet: function (d) {
                                return d.unit.name;
                            }},
                        {field: 'stores.name', title: __('Storesname'),width:100,templet: function (d) {
                                return d.stores.name;
                            }},

                        {field: 'number', title: __('Number'),templet: function (d) {
                                if(d.purchase_type==1){
                                    return (d.number).toFixed(number_decimal);
                                }
                                if(d.purchase_type==2){
                                    return '-'+(d.number).toFixed(number_decimal);
                                }
                            }},
                        {field: 'unit_price', title: __('Unit_price'),templet: function (d) {
                                return (d.unit_price).toFixed(price_decimal);
                            }},
                        {field: 'tax_included', title: __('含税单价'),templet: function (d) {
                                return (d.tax_included).toFixed(price_decimal);
                            }, hide:true},
                        {field: 'back_money', title: __('Back_money'),templet: function (d) {
                                return (d.back_money).toFixed(price_decimal);
                            }},
                        {field: 'all_money', title: __('All_money'),templet: function (d) {
                                if(d.purchase_type==1){
                                    return (d.all_money).toFixed(price_decimal);
                                }
                                if(d.purchase_type==2){
                                    return '-'+(d.all_money).toFixed(price_decimal);
                                }
                            }},
                        {field: 'period', title: __('Period'),templet: function (d) {
                                var str = ''
                                $.each(d.period, function(k, v) {
                                    str += v.serial+'<br>'
                                });
                                return str;
                            },minWidth:150},
                        {field: 'purchase_money', title: __('Purchase_money'), operate:'BETWEEN', hide:true},

                        {field: 'tax_money', title: __('税额'),hide:taxesStatus,templet: function (d) {
                                if(d.purchase_type==1){
                                    return (d.tax_money).toFixed(price_decimal);
                                }
                                if(d.purchase_type==2){
                                    return '-'+(d.tax_money).toFixed(price_decimal);
                                }
                            }},
                        {field: 'money_tax_price', title: __('价税合计'),hide:taxesStatus,templet: function (d) {
                                if(d.purchase_type==1){
                                    return (d.money_tax_price).toFixed(price_decimal);
                                }
                                if(d.purchase_type==2){
                                    return '-'+(d.money_tax_price).toFixed(price_decimal);
                                }
                            }},

                        {field: 'purchase_order_id', title: __('Purchase_order_id'), operate: 'LIKE', hide:true},
                        {field: 'date_range', title: __('时间期限'),  hide:true,minWidth:150},
                        {field: 'goods_number', title: __('询价条数'),  hide:true},
                        {field: 'remark', title: __('Remark')},
                        {field: 'note', title: __('Note'),templet: function (d) {
                                if(d.note!=null){
                                    return d.note;
                                }else{
                                    return '';
                                }
                            }},
                    ]],
                    done: function(res, curr, count){
                        //本地记录字段显示及宽度情况
                        tableColFilterAndWidth('table-goodssalesinfo', this)
                        layui.data('table-goodssalesinfo', {key: 'pagesize',value:this.limit});
                    }
                });
                //本地记录字段显示及宽度情况
                function tableColFilterAndWidth(dataKey, obj) {
                    // 初始化筛选状态
                    var local = layui.data(dataKey);
                    layui.each(obj.cols[0], function(index, item) {
                        if (item.field) {
                            var hide_key = item.field + '_hide';
                            var width_key = item.field + '_width';
                            if (hide_key in local) {
                                item.hide = local[hide_key];
                            }
                            if (width_key in local) {
                                item.width = local[width_key];
                            }
                        }
                    });
                    // 重新渲染表格以应用新的列配置
                    // 防止重复加载
                    if (!isReloading) {
                        isReloading = true;
                        table.reload('table', {cols: obj.cols})
                    }
                    //记录筛选状态
                    obj.elem.next().on('mousedown', 'input[lay-filter="LAY_TABLE_TOOL_COLS"]+', function(){
                        var input = $(this).prev()[0];
                        var key = input.name+'_hide';
                        console.log('LAY_TABLE_TOOL_COLS', key, input.checked)
                        layui.data(dataKey, {key: key,value: input.checked})
                    });
                    obj.elem.next().on('mouseup', 'th', function(){
                        var field = $(this).data('field')
                        var width = $(this).children('.layui-table-cell').css('width').replaceAll('px','');
                        field = field+'_width';
                        console.log('mouseup', field, width)
                        layui.data(dataKey, {key: field,value:width})
                    })
                }

                upload.render({
                    elem: '#import'
                    ,url: 'ajax/upload'
                    ,done: function(res, index, upload){ //上传后的回调
                         if(res.code==1){
                             Fast.api.ajax("kuerp/goods_sales_info/import?file="+res.data.url, "",'',true);
                         }else{
                             Toastr.error(res.msg);
                         }
                    }
                    ,accept: 'file' //允许上传的文件类型
                    ,size: 50 //最大允许上传的文件大小
                });

                //头工具栏事件
                table.on('toolbar(table)', function(obj){
                    var checkStatus = table.checkStatus(obj.config.id);
                    switch(obj.event){
                        case 'refresh':
                            table.reload('table', []);
                            break;
                        case 'add':
                            Fast.api.open("kuerp/goods_sales_info/add", "添加", {
                               callback:function(value){
                                  Controller.api.bindevent();
                               }
                            });
                        break;
                        case 'delAll':
                            var data = checkStatus.data;
                            var ids = '';
                            $(data).each(function (k,v) {
                                ids+=v.id+',';
                            });
                            Fast.api.ajax("kuerp/goods_sales_info/del?ids="+ids, function () {
                                reloadTable()
                            },'',true);
                        break;
                    }
                });
                function reloadTable(){
                    table.reload('table', {
                        where: {
                            filter:JSON.stringify(getSearch()),
                            op:JSON.stringify(getOp()),
                        }
                        ,page: {
                            curr: 1
                        }
                    });
                }
                //监听行工具事件
                table.on('tool(table)', function(obj){
                    var data = obj.data;
                    if(obj.event === 'del'){
                        $.ajax( {
                            url: "kuerp/goods_sales_info/del",
                            type: "POST",
                            data:{'ids':data.id},
                            success: function(res){
                                if(res.code==1){
                                    Toastr.success('操作成功');
                                    setTimeout(function () {
                                        reloadTable();
                                    },1000)
                                }else{
                                    Toastr.error(res.msg);
                                }
                            }
                        });
                    } else if(obj.event === 'edit'){
                        Fast.api.open("kuerp/goods_sales_info/edit?ids="+data.id, "编辑");
                    }
                });
                //搜索事件
                $('#search').on('click', function () {
                    table.reload('table', {
                        where: {
                            filter:JSON.stringify(getSearch()),
                            op:JSON.stringify(getOp()),
                        }
                        ,page: {
                            curr: 1
                        }
                    });
                });
                function getSearch() {
                    var search = {};
                    var purchase_code = $('#purchase_code').val();
                    if(purchase_code!=''){
                        search.purchase_code = purchase_code;
                    }
                    var customers_id = $('#customers_id').val();
                    if(customers_id!=''){
                        search.customers_id = customers_id;
                    }
                    var pay_status = $('#pay_status').val();
                    if(pay_status!=''){
                        search.pay_status = pay_status;
                    }
                    var examine_status = $('#examine_status').val();
                    if(examine_status!=''){
                        search.examine_status = examine_status;
                    }
                    var purchase_time = $('#purchase_time').val();
                    if(purchase_time!=''){
                        search.purchase_time = purchase_time;
                    }
                    var goods_type = $('#goods_type').val();
                    if(goods_type!=''){
                        search.goods_type = goods_type;
                    }
                    var goods_code = $('#goods_code').val();
                    if(goods_code!=''){
                        search.goods_code = goods_code;
                    }
                    var stores_id = $('#stores_id').val();
                    if(stores_id!=''){
                        search.stores_id = stores_id;
                    }
                    return search;
                }
                function getOp() {
                    var op = {};
                    op.purchase_code = 'LIKE';
                    op.purchase_time = 'RANGE';
                    op.goods_code = 'LIKE';
                    return op;
                }
            });
            Controller.api.bindevent();
        },
        
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        chosesale: function () {

            layui.use(['table','upload','form'], function(){
                var table = layui.table;
                upload = layui.upload;

                var set = Config.set;
                var price_decimal = parseInt(set.price_decimal.value);
                if(isNaN(price_decimal)){
                    price_decimal = 1;
                }
                var number_decimal = parseInt(set.number_decimal.value);
                if(isNaN(number_decimal)){
                    number_decimal = 1;
                }
                const q = {};
                location.search.replace(/([^?&=]+)=([^&]+)/g,function(_,k,v){q[k]=v});
                var filter = {}
                if (q.stores_id) {
                    $('#stores_id').val(q.stores_id)
                    filter.stores_id = q.stores_id
                }
                if (q.goods_code) {
                    $('#goods_code').val(q.goods_code)
                    filter.goods_code = q.goods_code
                }
                table.render({
                    elem: '#table'
                    ,url:'kuerp/goods_sales_info/chosesale'
                    ,where:filter
                    ,parseData: function(res){ //res 即为原始返回的数据
                        return {
                            "code": 0, //解析接口状态
                            "msg": '', //解析提示文本
                            "count": res.total, //解析数据长度
                            "data": res.rows //解析数据列表
                         };
                    }
                    ,toolbar: '#thisToolbar' //开启头部工具栏，并为其绑定左侧模板
                    ,height: 'full-180'
                    ,page: true
                    ,limit: 50
                    ,limits: [10,20,30,50,100,150, 200]
                    ,cellMinWidth: 100 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    ,cols: [[
                        {field: 'purchase_time', title: __('Purchase_time'),width:120,templet: function (d) {
                                return layui.util.toDateString(d.purchase_time*1000,'yyyy-MM-dd');
                            }},
                        {field: 'purchase_code', title: __('Purchase_code'), width:170},
                        {field: 'staff_member.name', title: __('Sale_user'),templet: function (d) {
                                if(d.staff_member.name!=null){
                                    return d.staff_member.name;
                                }else{
                                    return '';
                                }
                            }},
                        {field: 'customers.customer_name', title: __('Customers_id'),templet: function (d) {
                                if(d.customers.customer_name!=null){
                                    return d.customers.customer_name;
                                }else{
                                    return '';
                                }
                            },minWidth:150},
                        {field: 'goods_code', title: __('Goods_code'), operate: 'LIKE'},
                        {field: 'goods.goods_name', title: __('Goods_name'),templet: function (d) {
                                return d.goods.goods_name;
                            }},
                        {field: 'goods_type', title: __('购买类型')},
                        {field: 'unit.name', title: __('Unitname'),width:100,templet: function (d) {
                                return d.unit.name;
                            }},
                        {field: 'stores.name', title: __('Storesname'),width:100,templet: function (d) {
                                return d.stores.name;
                            }},

                        {field: 'number', title: __('Number'),templet: function (d) {
                                if(d.purchase_type==1){
                                    return (d.number).toFixed(number_decimal);
                                }
                                if(d.purchase_type==2){
                                    return '-'+(d.number).toFixed(number_decimal);
                                }
                            }},
                        {field: 'unit_price', title: __('Unit_price'),templet: function (d) {
                                return (d.unit_price).toFixed(price_decimal);
                            }},
                        
                        {field: 'period', title: __('Period'),templet: function (d) {
                                var str = ''
                                $.each(d.period, function(k, v) {
                                    str += v.serial+'<br>'
                                });
                                return str;
                            },minWidth:150},
                        {field: 'note', title: __('Note'),templet: function (d) {
                                if(d.note!=null){
                                    return d.note;
                                }else{
                                    return '';
                                }
                        },hide:true},
                        {fixed:'right',field: 'operate2',operate:false, title: __('Operate'), templet: function (d) {
                                return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs" lay-event="choose"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                        }},
                    ]],
                    done: function(res, curr, count){
                        // $(".layui-table-body  tr").resize(function () {
                        //     $(".layui-table-body  tr").each(function (index, val) {
                        //         $($(".layui-table-fixed .layui-table-body table tr")[index]).height($(val).height());
                        //     });
                        // });
                        $(".layui-table-body  tr").each(function (index, val) {
                            $($(".layui-table-fixed .layui-table-body table tr")[index]).height($(val).height());
                        });
                    }
                });

                //头工具栏事件
                table.on('toolbar(table)', function(obj){
                    var checkStatus = table.checkStatus(obj.config.id);
                    switch(obj.event){
                        case 'refresh':
                            table.reload('table', []);
                            break;
                    }
                });
                //监听行工具事件
                table.on('tool(table)', function(obj){
                    var data = obj.data;
                    if(obj.event === 'choose'){
                        Fast.api.close({id: data.id, name: data.purchase_code,customer_name:data.customers.customer_name});
                    }
                });
                //搜索事件
                $('#search').on('click', function () {
                    reloadTable()
                });
                function reloadTable(){
                    table.reload('table', {
                        where: {
                            filter:JSON.stringify(getSearch()),
                            op:JSON.stringify(getOp()),
                        }
                        ,page: {
                            curr: 1
                        }
                    });
                }
                function getSearch() {
                    var search = {};
                    var purchase_code = $('#purchase_code').val();
                    if(purchase_code!=''){
                        search.purchase_code = purchase_code;
                    }
                    var customers_id = $('#customers_id').val();
                    if(customers_id!=''){
                        search.customers_id = customers_id;
                    }
                    var pay_status = $('#pay_status').val();
                    if(pay_status!=''){
                        search.pay_status = pay_status;
                    }
                    var examine_status = $('#examine_status').val();
                    if(examine_status!=''){
                        search.examine_status = examine_status;
                    }
                    var purchase_time = $('#purchase_time').val();
                    if(purchase_time!=''){
                        search.purchase_time = purchase_time;
                    }
                    var goods_type = $('#goods_type').val();
                    if(goods_type!=''){
                        search.goods_type = goods_type;
                    }
                    var goods_code = $('#goods_code').val();
                    if(goods_code!=''){
                        search.goods_code = goods_code;
                    }
                    var stores_id = $('#stores_id').val();
                    if(stores_id!=''){
                        search.stores_id = stores_id;
                    }
                    return search;
                }
                function getOp() {
                    var op = {};
                    op.purchase_code = 'LIKE';
                    op.purchase_time = 'RANGE';
                    op.goods_code = 'LIKE';
                    return op;
                }
            });
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                layui.use('laydate', function(){
                    var laydate = layui.laydate;
                    //执行一个laydate实例
                    
                    laydate.render({
                        elem: '#c-purchase_time',
                        type: 'datetime'
                    });
                    laydate.render({
                         elem: '#purchase_time',
                         type: 'datetime',
                         range: true
                    });
                    laydate.render({
                        elem: '#c-delivery_time',
                        type: 'datetime'
                    });
                    laydate.render({
                         elem: '#delivery_time',
                         type: 'datetime',
                         range: true
                    });
                });
                Form.api.bindevent($("form[role=form]"), function(data, ret){
                    parent.location.reload();
                });
            }
        }
    };
    return Controller;
});